package com.frame.work.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.frame.work.entity.TblMessage;
import com.frame.work.service.TblMessageService;
import com.mysql.cj.log.Log;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author wjming
 */
@Component
@Slf4j
public class UserLogMessageListen {

    @Autowired
    private TblMessageService tblMessageService;

    /**
     * 消息处理
     */
    @RabbitListener(queues = "${topic.rabbit.userAddTransferHomeMessage}")
    public void clearDeviceDelGroup(Map<String, String> getMap, Channel rabbitChannel, @Headers Map<String, Object> headers) {
        RabbitmqEnum action = RabbitmqEnum.RETRY;
        try {
            TblMessage message = JSON.parseObject(JSON.toJSONString(getMap), TblMessage.class);
            this.tblMessageService.insert(message);
            action = RabbitmqEnum.ACCEPT;
        } catch (Exception e) {
            log.error("异常丢弃的数据:[frameDeal] -> [message:{} ] ->[Exception: {}]", getMap.toString(), e.getCause());
            action = RabbitmqEnum.REJECT;
        } finally {
            try {
                //通过finally块来保证ACK/NACK会执行一次
                if (action.equals(RabbitmqEnum.ACCEPT)) {
                    rabbitChannel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), true);
                } else if (action.equals(RabbitmqEnum.RETRY)) {
                    rabbitChannel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, true);
                } else {
                    rabbitChannel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, false);
                }

            } catch (Exception e) {
                log.error("rabbitmq回应应答失败[errorBasicNack] -> [gatewayMac:{}] ->[Exception: {}]", getMap.toString(), e.getCause());
            }
        }
    }
}
